#include "trans.h"

int sendFile(int sockfd,char* buf,int flag){


    //目前没有加入断点重传
    train_t train;
    train.flag = flag;
    if(train.flag != PUTS){//PUTS 代表的是发文件
        printf("不是发送对应的命令！\n");
        exit(1);
    }
    //进入这里说明传入的是 PUTS 命令
    train.length = strlen(buf);
    char filename[4096] = {0};
    //将文件名拷贝过来
    memcpy(filename,buf,train.length);
    //这两个本质上是一样的，但是便于后续操作，就定义了两个
    memcpy(train.data,buf,train.length);
    //发送文件名
    send(sockfd,&train,sizeof(train.flag)+sizeof(train.length)+train.length,MSG_NOSIGNAL);

    int filefd = open(filename,O_RDONLY);


    struct stat statbuf;
    fstat(filefd,&statbuf);
    //发送文件大小（以off_t方式）
    off_t filesize=statbuf.st_size;
    train.length=sizeof(off_t);
    memcpy(train.data,&filesize,sizeof(off_t));
    send(sockfd,&train,sizeof(train.flag)+sizeof(train.length)+train.length,MSG_NOSIGNAL);
    if(filesize<=104857600){//文件＜=100MB时，逐块读取并发送
        while(1){
            bzero(train.data,sizeof(train.data));
            ssize_t ret=read(filefd,train.data,sizeof(train.data));
            train.length=ret;//记录实际读取的字节数
                             //发送数据块
            send(sockfd,&train,sizeof(train.flag)+sizeof(train.length)+train.length,MSG_NOSIGNAL);
            if(ret==0){//读取完毕，退出循环
                break;
            }
        }
    }else{//超过100MB的大文件直接发送
        sendfile(sockfd,filefd,0,filesize);
    }
    close(filefd);

    return 0;
}
